package com.nexus.all.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nexus.all.dto.NoteWordQueryDTO;
import com.nexus.all.manager.NoteWordManager;
import com.nexus.all.model.NoteWord;
import com.nexus.all.service.NoteWordService;
import com.nexus.bean.utils.CollectionsUtil;
import com.nexus.bean.utils.StringUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@AllArgsConstructor
public class NoteWordServiceImpl implements NoteWordService {

    private final NoteWordManager noteWordManager;

    @Override
    public List<String> queryNoteWord(NoteWordQueryDTO dto) {
        if (StringUtils.isBlank(dto.getKeyword())) {
            return new ArrayList<>();
        }
        Page<NoteWord> page = noteWordManager.queryNoteWord(dto);
        List<NoteWord> records = page.getRecords();
        if (CollectionsUtil.isEmpty(records)) {
            return new ArrayList<>();
        }
        for (NoteWord record : records) {
            //关键词做高亮
            if (StringUtils.isNotBlank(dto.getKeyword())) {
                String formattedKeyword = String.format("<b>%s</b>", dto.getKeyword());
                record.setNoteWord(record.getNoteWord().replaceFirst(dto.getKeyword(), formattedKeyword));
            }
        }
        return records.stream().map(NoteWord::getNoteWord).collect(Collectors.toList());
    }
}
